package com.sfddata.musicpillow.user.controller;

import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sfddata.musicpillow.common.constant.BizCodeEnum;
import com.sfddata.musicpillow.common.respose.BaseRespose;
import com.sfddata.musicpillow.user.entity.*;
import com.sfddata.musicpillow.user.feign.ThirdpartyFeignService;
import com.sfddata.musicpillow.user.service.MonthReportInfoService;
import com.sfddata.musicpillow.user.service.ReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import com.sfddata.musicpillow.user.service.TbSleepRecordService;
import com.sfddata.musicpillow.common.utils.PageUtils;
import com.sfddata.musicpillow.common.utils.R;
import org.springframework.web.multipart.MultipartFile;


/**
 *
 *
 * @author jyo
 * @email 820389501@qq.com
 * @date 2022-11-02 15:29:15
 */
@RestController
@RequestMapping("/algorithm")
public class TbSleepRecordController {

    // 注入logger
    private final static Logger logger = LoggerFactory.getLogger(TbSleepRecordController.class);

    @Autowired
    private TbSleepRecordService tbSleepRecordService;

    @Autowired
    private ThirdpartyFeignService thirdpartyFeignService;

    @Autowired
    private ReportService reportService;

    @Autowired
    private MonthReportInfoService monthReportInfoService;


    /**
     * 获取日历
     * @param
     * @return
     */
    @RequestMapping("/getDateList")
    public BaseRespose<MonthList> getDateList(@RequestHeader Long id){

        BaseRespose<MonthList> respose = new BaseRespose<>();
        ArrayList<String> dateList = tbSleepRecordService.getByUserId(id);

        ArrayList<String> isreadList = tbSleepRecordService.getIsReadList(id);

        MonthList monthList = new MonthList();
        monthList.setHaveReport(isreadList);
        monthList.setUnRead(dateList);

        respose.setCode(BizCodeEnum.SUCCESS.getCode());
        respose.setMsg(BizCodeEnum.SUCCESS.getMsg());
        if (dateList != null){
            respose.setData(monthList);
        }
        return respose;
    }

    @RequestMapping("/getMonthList")
    public BaseRespose<MonthList> getMonthList(@RequestHeader Long id){
        BaseRespose<MonthList> respose = new BaseRespose<>();
        MonthList dateList = monthReportInfoService.getByUserId(id);

        respose.setCode(BizCodeEnum.SUCCESS.getCode());
        respose.setMsg(BizCodeEnum.SUCCESS.getMsg());
        if (dateList != null){
            respose.setData(dateList);
        }
        return respose;
    }


    @RequestMapping("/saveRecord")
    public BaseRespose<CompareEntity> saveRecord(@RequestBody SleepRecordEntityVo sleepRecordEntityVo) throws ParseException {

        if ( sleepRecordEntityVo.getSleepTime().equals("-4") ){

            sleepRecordEntityVo.setSleepTime("0");
            sleepRecordEntityVo.setBedTime(
                    sleepRecordEntityVo.getWakingTime()
            );
        }

        BaseRespose<CompareEntity> respose = new BaseRespose<>();
        // 需要和前一天的记录 对比分数上升或者下降了多少，还有深和浅是上升还是下降
        CompareEntity compare = tbSleepRecordService.compareRecord(sleepRecordEntityVo);
        Long recordId = new Long(0);
        recordId = tbSleepRecordService.saveByVo(sleepRecordEntityVo);
        respose.setCode(BizCodeEnum.SUCCESS.getCode());
        respose.setMsg(BizCodeEnum.SUCCESS.getMsg());
        compare.setRecordId(recordId);
        if (compare != null){
            respose.setData(compare);
        }
        return respose;
    }

    @RequestMapping("/uploadFiles")
    public BaseRespose<String> uploadFiles(@RequestParam ArrayList<MultipartFile> fileList, @RequestParam Long recordId) throws IOException {

        BaseRespose<String> respose2 = new BaseRespose<>();
        if (recordId == null) {

            respose2.setCode(BizCodeEnum.UNKNOW_RECORDID.getCode());
            respose2.setMsg(BizCodeEnum.UNKNOW_RECORDID.getMsg());
            return respose2;
        }

        ArrayList<String> addrlist = new ArrayList<>();
        // 一个文件一个文件的传
        for (MultipartFile multipartFile : fileList) {
            BaseRespose<String> respose = thirdpartyFeignService.uploadwav(multipartFile);
            String data = respose.getData();
            addrlist.add(data);
        }
        TbSleepRecordEntity record = tbSleepRecordService.getById(recordId);
        record.setColAudioData(addrlist.toString());
        tbSleepRecordService.updateById(record);

        respose2.setCode(BizCodeEnum.SUCCESS.getCode());
        respose2.setMsg(BizCodeEnum.SUCCESS.getMsg());
        return respose2;
    }


    @RequestMapping("/getRecord")
    public BaseRespose<TbSleepRecordEntityVo> getRecord(@RequestHeader Long id, @RequestParam String date) throws ParseException {

        BaseRespose<TbSleepRecordEntityVo> respose = new BaseRespose<>();
        TbSleepRecordEntity sleepRecord;
        TbSleepRecordEntityVo sleepRecordEntity = new TbSleepRecordEntityVo();
        try {
            QueryWrapper<TbSleepRecordEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("col_user_id", id);
            queryWrapper.eq("col_date", date);
            sleepRecord = tbSleepRecordService.getOne(queryWrapper);

            sleepRecordEntity = tbSleepRecordService.convertDate(sleepRecord);
            sleepRecord.setIsRead(1);
            tbSleepRecordService.updateById(sleepRecord);

        }catch (Exception e){
            respose.setCode(BizCodeEnum.DATA_IS_NULL.getCode());
            respose.setMsg(BizCodeEnum.DATA_IS_NULL.getMsg());
            respose.setMsg(e.getMessage());
            return respose;
        }

        CompareEntity compare = tbSleepRecordService.compareRecord(sleepRecord);

        respose.setCode(BizCodeEnum.SUCCESS.getCode());
        respose.setMsg(BizCodeEnum.SUCCESS.getMsg());
        sleepRecordEntity.setCompareEntity(compare);
        respose.setData(sleepRecordEntity);

        return respose;
    }

    @GetMapping("/getRecordForIndex")
    public BaseRespose<RecordForIndexEntity> getRecordForIndex(@RequestParam Long userId) throws ParseException {

        BaseRespose<RecordForIndexEntity> respose = new BaseRespose<>();

        // 现在的时间
        String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        RecordForIndexEntity entity = tbSleepRecordService.getRecordForIndex(userId, nowTime);

        respose.setCode(BizCodeEnum.SUCCESS.getCode());
        respose.setMsg(BizCodeEnum.SUCCESS.getMsg());
        respose.setData(entity);
        return respose;

    }

    /**
     * 获取周报
     * @param
     * @param date
     * @return
     */
    @RequestMapping("/getWeekRecord")
    public BaseRespose<WeekReportInfoVo> getWeekRecord(@RequestHeader Long id, @RequestParam String date) throws ParseException {


        BaseRespose<WeekReportInfoVo> respose = new BaseRespose<>();
        WeekReportInfoVo weekReport = reportService.getWeekReport(id, date);
        // 填写对比数据并且转成list

        if (weekReport == null){
            respose.setCode(BizCodeEnum.WEEK_NOTENOUGH.getCode());
            respose.setMsg(BizCodeEnum.WEEK_NOTENOUGH.getMsg());
            return respose;
        }

        respose.setCode(BizCodeEnum.SUCCESS.getCode());
        respose.setMsg(BizCodeEnum.SUCCESS.getMsg());
        respose.setData(weekReport);
        return respose;
    }

    /**
     * 获取月报
     * @param
     * @param date
     * @return
     */
    @RequestMapping("/getMonthRecord")
    public BaseRespose<MonthReportInfoVo> getMonthRecord(@RequestHeader Long id, @RequestParam String date) throws ParseException {

        BaseRespose<MonthReportInfoVo> respose = new BaseRespose<>();
        MonthReportInfoVo monthreport = reportService.getMonthReport(id, date);

        if (monthreport == null){
            respose.setCode(BizCodeEnum.MONTH_NOTENOUGH.getCode());
            respose.setMsg(BizCodeEnum.MONTH_NOTENOUGH.getMsg());
            return respose;
        }

        respose.setCode(BizCodeEnum.SUCCESS.getCode());
        respose.setMsg(BizCodeEnum.SUCCESS.getMsg());
        respose.setData(monthreport);
        return respose;
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("user:tbsleeprecord:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tbSleepRecordService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("user:tbsleeprecord:info")
    public R info(@PathVariable("id") Long id){



		TbSleepRecordEntity tbSleepRecord = tbSleepRecordService.getById(id);

        return R.ok().put("tbSleepRecord", tbSleepRecord);
    }


    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("user:tbsleeprecord:save")
    public R save(@RequestBody TbSleepRecordEntity tbSleepRecord){
		//tbSleepRecordService.save(tbSleepRecord);

        System.out.println(tbSleepRecord);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("user:tbsleeprecord:update")
    public R update(@RequestBody TbSleepRecordEntity tbSleepRecord){
		tbSleepRecordService.updateById(tbSleepRecord);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("user:tbsleeprecord:delete")
    public R delete(@RequestBody Long[] ids){
		tbSleepRecordService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
